package com.jb.charts;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.List;


public class CSVLoader implements ChartModel
{
    private int columns;
    private int rows;
    private String url="/com/jb/charts/dow.csv";
    private String xLables[];
    private double[][] values;
    private String[] legends;
    
    public CSVLoader() {
        load("/com/jb/charts/dow.csv");
    }
    
    public int getSeries() {
        return columns;
    }
    
    public String[] getXLabels() {
        return xLables;
    }
    
    public double[][] getData() {
        return values;
    }
    
    public String[] getLegends (){
       return legends;
    }
    public void load(String url) {
        try {
            InputStream is =getClass().getResourceAsStream(url);
            if(is==null)
                return;
            BufferedReader bf = new BufferedReader(new InputStreamReader(is));
            String line = bf.readLine();
            List list = new ArrayList();
            columns =0;
            while (line != null) {
                if (line != null && line.trim().length() > 0) {
                    String [] cols = line.split(",");
                    if(columns<cols.length)
                        columns=cols.length;
                    list.add(line.split(","));
                }
                line = bf.readLine();
            }
            this.rows = list.size()-1;
            this.columns = 1;
            
            values=new double[columns][rows];
            xLables=new String[rows];
            legends=new String[columns];
            int size = list.size();
            for(int i=0; i<size;i++) {
                String[] row=(String[])list.get(i);
                
                if(i==0) {
                    for(int j=0;j<columns;j++)
                        legends[j]=row[j+1];
                    continue;
                }
                
                this.xLables[size-i-1]=row[0];
                for(int j=0;j<columns;j++) {
                    values[j][size-i-1]= Double.parseDouble(row[j+1]);                           
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new CSVLoader();
    }
    public void setUrl(String param) {
        if(param!=null&&!param.equals(url))
        {
            this.url = param;
            load(this.url);
        }
    }
    
    public String getUrl() {
        return url;
    }
}
